class MicropostsController < ApplicationController
  # 引入会话帮助器
  include SessionsHelper
  before_action :set_micropost, only: %i[ show edit update destroy ]

  # GET /microposts or /microposts.json
  def index
    @microposts = Micropost.all
  end

  # GET /microposts/1 or /microposts/1.json
  def show
    # 隐藏写法
    # @micropost = Micropost.
  end

  # GET /microposts/new
  def new
    @micropost = Micropost.new
  end

  # GET /microposts/1/edit
  def edit
  end

  # GET /microposts/recent
  def recent
    @microposts = Micropost.order(created_at: :desc).limit(10)
  end

  # GET /microposts/popular
  def popular
    @microposts = Micropost.order(created_at: :desc).limit(10)
  end

  # GET /microposts/hot
  def hot
    @microposts = Micropost.order(created_at: :desc).limit(10)
  end

  # GET /microposts/:id/like
  def like
    @micropost = Micropost.find(params[:id])
  end

  # POST /microposts or /microposts.json
  def create
    logger.info "current_user = #{current_user}"

    # 检查用户是否登录
    unless logged_in?
      redirect_to login_path, notice: "请先登录"
      return
    end

    # 接受表单参数
    @micropost = Micropost.new(micropost_params)
    # 基于会话获取当前用户
    @micropost.user_id = current_user.id

    respond_to do |format|
      if @micropost.save
        format.html { redirect_to @micropost, notice: "Micropost was successfully created." }
        format.json { render :show, status: :created, location: @micropost }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @micropost.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /microposts/1 or /microposts/1.json
  def update
    respond_to do |format|
      if @micropost.update(micropost_params)
        format.html { redirect_to @micropost, notice: "Micropost was successfully updated." }
        format.json { render :show, status: :ok, location: @micropost }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @micropost.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /microposts/1 or /microposts/1.json
  def destroy
    @micropost.destroy!

    respond_to do |format|
      format.html { redirect_to microposts_path, status: :see_other, notice: "Micropost was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_micropost
      @micropost = Micropost.find(params.expect(:id))
    end

    # Only allow a list of trusted parameters through.
    def micropost_params
      # 设置入参必填项
      params.expect(micropost: [ :content ])
    end
end
